package com.shhic.hhplt.server.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import com.shhic.hhplt.server.service.ITestReportService;
import com.shhic.hhplt.server.service.ITestReportXmlPersist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shhic.hhplt.server.biz.ITestReportHelper;
import com.shhic.hhplt.server.exceptions.TestReportXmlException;
import com.shhic.hhplt.testreport.TestReport;

@Component
public class ReportXmlDbPersist implements ITestReportXmlPersist {
	@Autowired
	ITestReportService trService;
	@Resource ITestReportHelper testReportHelper;
	
	@Override
	public String generateNewReportLoc(String productName, String barCode) {
		return String.format("%s\\%s\\%s", 
				productName,
				new SimpleDateFormat("yyyy-MM-dd").format(new Date()),
				productName+"_"+barCode
		);
	}
	
	@Override
	public TestReport getTestReport(String reportLoc)throws TestReportXmlException {
		String testReportXml = trService.getTestReportXml(reportLoc);
		if(testReportXml == null){
			return null;
		}
		return testReportHelper.generateTestReportFromXml(testReportXml);
	}
	
	@Override
	public void saveOrUpdateReportXml(TestReport report, String persistLocation)throws TestReportXmlException {
		String reportXmlStr = testReportHelper.generateXmlStrFromTestReport(report);
		if(trService.getTestReportXml(persistLocation)!=null){
			trService.updateTestReportXml(persistLocation,reportXmlStr);
		}else{
			trService.insertTestReportXml(persistLocation,reportXmlStr);
		}
	}
	
}
